import React from 'react'
import { Upload, message, Icon } from 'antd'

class ImageUpload extends React.Component {
    beforeUpload = file => {
        const isType = file.type === 'image/jpg' || file.type === 'image/jpeg' || file.type === 'image/bmp'
        const isLt10M = file.size / 1024 / 1024 < 10

        if (!isType) {
            message.info('仅支持.jpg、.jpeg、.bmp格式！')
            return isType
        }

        if (!isLt10M) {
            message.info('图片大小不能超过10MB！')
            return isLt10M
        }
    }

    handleChange = ({ file, fileList }) => {
        if (file.response && file.response.code !== 1) {
            message.info(file.response.data)
            this.props.onChangeState({ picUrl: [] })
            return
        }

        if (!file.status) {
            this.props.onChangeState({ picUrl: [] })
            return
        }

        if (file.status === 'done') {
            this.props.onChangeFormData('image', file.response.data)
        }

        if (file.response) {
            fileList.forEach(item => item.url = item.response.data)
        }

        this.props.onChangeState({ picUrl: fileList })
    }

    handleRemove = () => {
        this.props.onChangeFormData('image', '')
    }

    render() {
        const { fileUrl } = this.props
        const uploadButton = (
            <div>
                <Icon type="plus" />
                <div className="ant-upload-text">上传图片</div>
            </div>
        )

        return (
            <Upload 
                action="api/UploadFile/UploadImg"
                accept="image/bmp, image/jpeg, image/jpg"
                headers={{ Authorization: localStorage.token }}
                listType="picture-card"
                fileList={ fileUrl }
                beforeUpload={ this.beforeUpload }
                onChange={ this.handleChange }
                onRemove={ this.handleRemove }
            >
                { fileUrl.length ? null : uploadButton }
            </Upload>
        )
    }
}

export default ImageUpload